package m2_work;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140"); //www.wht6.cn
        f.setPort(5672); //默认端口可以省略
        f.setUsername("admin");
        f.setPassword("admin");
        // f.setVirtualHost("/xxxx");

        Channel c = f.newConnection().createChannel();

        //定义队列
        c.queueDeclare(
                "task_queue",
                true,
                false,
                false,
                null);

        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                System.out.println("收到： "+msg);
                // "sdf...sdewr....gdfg...."
                for (int i = 0; i < msg.length(); i++) {
                    if (msg.charAt(i) == '.') {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                //.getDeliveryTag() 获取回执
           c.basicAck(message.getEnvelope().getDeliveryTag(),false);
                System.out.println("消息处理结束");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };
        c.basicQos(1);
        //消费数据、接收数据
        c.basicConsume(
                "task_queue",
                false,//关闭自动确认，改成手动确认
                deliverCallback,
                cancelCallback);

    }
    }
